package com.whucke.im.utils;

import com.alibaba.fastjson.JSON;
import com.whucke.im.vo.JsonResult;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * http工具
 *
 * @author Zhang Peng
 * @since 2019/2/20 17:13
 */
@Component
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final MediaType MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");

    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 获取request对象
     *
     * @param uri    URI
     * @param method 请求方法
     * @param params 请求参数
     * @return
     */
    public DefaultFullHttpRequest getRequest(String uri, HttpMethod method, Map<String, Object> params) {
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri, Unpooled.copiedBuffer(JSON.toJSONString(params).getBytes()));
        request.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
        request.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
        request.headers().set(HttpHeaderNames.CONTENT_ENCODING, "UTF-8");
        return request;
    }

    /**
     * 请求结果转换
     *
     * @param result
     * @return
     */
    public JsonResult resultConvert(String result) {
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        return JSON.parseObject(result, JsonResult.class);
    }

    /**
     * post 请求
     *
     * @param url      请求路径
     * @param JsonBody body参数
     * @return
     */
    public JsonResult doPost(String url, String JsonBody) {
        RequestBody body = RequestBody.create(MEDIA_TYPE, JsonBody);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return resultConvert(response.body().string());
        } catch (Exception e) {
            logger.info("{} 请求错误，原因：{}", url, e.getMessage());
        }
        return null;
    }

    /**
     * get请求
     *
     * @param url    请求路径
     * @param params 参数
     * @return
     */
    public JsonResult doGet(String url, Map<String, String> params) {
        if (!CollectionUtils.isEmpty(params)) {
            StringBuilder sb = new StringBuilder("?");
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
            String paramChain = sb.toString();
            String param = paramChain.substring(0, paramChain.length() - 1);
            url = url + param;
        }
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return resultConvert(response.body().string());
        } catch (Exception e) {
            logger.info("{} 请求错误，原因：{}", url, e.getMessage());
        }
        return null;
    }

}
